# 类型转换 🏀

# 🏀 int: 只能转换由纯数字组成的字符串

# 浮点型 => int


print(int(1.2))  # 1
print(int(1.8))  # 1

# 字符串 => int
print(int("123"))  # 123
print(int("-123"))  # -123

# 字符串 => int 失败
# print(int("123a")) # ValueError: invalid literal for int() with base 10: '123a'

# 字符串 => int 失败
# print(int("123.4")) # ValueError: invalid literal for int() with base 10: '123.4'

# 字符串 => int 失败
# print(int("a123")) # ValueError: invalid literal for int() with base 10: 'a123'

# 字符串 => int 失败
print(int("+1233"))  # 1233
print(int("-1233"))  # -1233

# 字符串中如何包含 字母, 小数点, 正负号(非开头位置), 空格等, 都会导致转换失败


print("-------------float()----------------------")
# 🏀 float
print(float("123"))  # 123.0
print(float("123.4"))  # 123.4
print(float("-123"))  # -123.0
print(float("-123.4"))  # -123.4

print("-------------str()----------------------")
# str: 任何类型都可以转成字符型
n = 100
print(str(n))
print(type(str(n)))  # <class 'str'>

li = [1, 2, 3]
print(str(li))


print("-------------eval()----------------------")

# eval: 执行字符次表达式，并返回值
print(eval("123"))  # 123
print(eval("123.4"))  # 123.4
print(eval("-123"))  # -123
print(eval("-123.4"))  # -123.4
print(eval("10+10"))  # 20
print(eval("10-10"))  # 0
print(eval("10*10"))  # 100
print(eval("10/10"))  # 1.0
print(eval("10//10"))  # 1
print(eval("10%10"))  # 0
print(eval("10**10"))  # 10000000000

str = "[1,2,3,4,[5,6]]"
print(eval(str))  # [1,2,3,4,[5,6]]
print(type(eval(str)))  # <class 'list'>

dict = "{'n':2,'a':4}"
print(eval(dict))  # {'n': 2, 'a': 4}
print(type(eval(dict)))  # <class 'dict'>


print("-------------list()----------------------")
# list(): 可迭代对象转成列表
# 支持类型: str, tuple, dict, set
print(list("123"))  # str ['1', '2', '3']
print(list((1, 2, 3)))  # tuple [1, 2, 3]
print(list({"n": 2, "a": 4}))  # dict ['n', 'a'] key name as list
print(list({1, 2, 2, 3, 3}))  # set [1, 2, 3]


# 和 javascript 对比
# ------------------------------------------------------
# Python                        Javascript             #
# ------------------------------------------------------
# list []                         Array                #
# ------------------------------------------------------
# tuple ()                        Object.freeze(obj)   #
# ------------------------------------------------------
# dict  {k:v, k:v}                Object / Map         #
# ------------------------------------------------------
# set  {ele,ele}                  Set                  #
# ------------------------------------------------------
